package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义过滤器
 */
@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 加在前置过滤器的第6个 位置
     */
    @Override
    public int filterOrder() {
        return 6;
    }
    /*
    针对当前请求进行判断，判断当前请求是否要执行这个过滤器的过滤代码
    如果访问item-service 设置权限
    如果访问其他服务   不设置权限
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取当前请求的服务id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        if(serviceId.equals("item-service")){
            return true;//进行过滤
        }
        return false;//不进行过滤
    }
    /*
    过滤代码，对用户权限进行检查
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            //设置阻止请求
            ctx.setSendZuulResponse(false);
            //向客户端相应
            ctx.setResponseStatusCode(200);
            ctx.setResponseBody(JsonResult.err().code(JsonResult.NOT_LOGIN).msg("do login!!").toString());
        }
        return null;
    }
}
